// pages/bind/bind.js
const app = getApp();
import {
  request
} from "../../utils/request";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    openid: "",
    identifier: "",
    showKeyboard: false,
    step: 1, // 1=省份简称，2=字母数字

    provinces: [
      "京","津","冀","晋","蒙","辽","吉","黑",
      "沪","苏","浙","皖","闽","赣","鲁","豫",
      "鄂","湘","粤","桂","琼","甘","陕","贵",
      "云","川","渝","藏","宁","新","港","澳","台"
    ],
    letters: "ABCDEFGHJKLMNPQRSTUVWXYZ".split(""), // 车牌里没有 I 和 O
    numbers: "0123456789".split(""),

    bindId: null,
    phone: "",
    vehicleNo: "",
    color: "",
    message: "您好，临时停车，请多包涵。如果需要挪车，请随时联系我，我会尽快赶来。感谢您的理解！",


    phoneError: false,
    phoneErrorMessage: ''
  },

  onShowKeyboard() {
    this.setData({ showKeyboard: true, step: 1 });
  },

  onCloseKeyboard() {
    this.setData({ showKeyboard: false });
  },

  onKeyTap(e) {
    const key = e.currentTarget.dataset.key;
    let { vehicleNo, step } = this.data;

    // 第一步：省份简称
    if (step === 1) {
      vehicleNo = key;
      step = 2; // 下一步进入字母数字键盘
    } 
    // 第二步：字母数字
    else if (step === 2) {
      if (vehicleNo.length < 8) {
        vehicleNo += key;
      }
    }

    this.setData({ vehicleNo, step });
  },

  onDelete() {
    let { vehicleNo, step } = this.data;
    if (vehicleNo.length > 0) {
      vehicleNo = vehicleNo.slice(0, -1);
      if (vehicleNo.length === 0) {
        step = 1; // 回到省份键盘
      }
    }
    this.setData({ vehicleNo, step });
  },

  onConfirm() {
    this.setData({ showKeyboard: false });
  },

  bind() {
    const postData = {
      ...this.data
    };
    request({ url: "mini-code-bind/bind", method: "POST", data: postData })
      .then(() => {
        wx.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 1000,
          success: () => {
            setTimeout(() => {
              wx.reLaunch({
                url: '/pages/index/index',
              });
            }, 1000);
          }
        });
      })
      .catch(err => console.error("注册失败", err));
  },

  onPhoneChange(e) {
    const value = e.detail; // van-field change 事件返回输入值
    this.setData({ phone: value });

    // 校验手机号格式
    if (!/^1[3-9]\d{9}$/.test(value)) {
      this.setData({
        phoneError: true,
        phoneErrorMessage: '请确认手机号是否正确😊'
      });
    } else {
      this.setData({
        phoneError: false,
        phoneErrorMessage: ''
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (app.globalData.openid) {
      this.setData({
        openid: app.globalData.openid,
        identifier: options.scene
      });
    }
    if (options.isSelf === 'true') {
      request({
        url: `mini-code-bind/info/${this.data.identifier}`,
        method: "GET"
      })
        .then(res => {
          this.setData({
            bindId: res.bindId,
            phone: res.phone,
            vehicleNo: res.vehicleNo,
            color: res.color,
            message: res.message
          });
        })
        .catch(err => console.error("查询小程序码数据失败", err));
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})